import Singleton from "../base/Singleton";
import { TimeTools } from "../common/TimeTools";
import { Tools } from "../common/Tools";
import { ANSWER_STATE_ENUM, BUNDLE_TYPE_ENUM, GAME_TYPE_ENUM, RELEASE_TYPE_ENUM } from "../base/EnumIndex";
import { LvInfo } from "../model/OtherModel";
import { ResManager1 } from "./ResManager1";
import { UIManager } from "./UIManager";
import { AdManager } from "../ads/AdManager";
import { AdManager_ZJ } from "../ads/AdManager_ZJ";
import { NetworkManager } from "./NetworkManager";
import { AdManager_WX } from "../ads/AdManager_WX";
import { AdManager_KS } from "../ads/AdManager_KS";

const unlockAllTime: number = 24;      //看视频解锁的全部关 多少小时  就要锁上
const unlockAllTime2: number = 6;      //看视频解锁的全部关 多少小时  就要锁上
const levelTimeLock: number = 24;      //看视频解锁的关 多少小时  就要锁上
const tipTimeLock: number = 24;      //提示过多少小时  就要锁上
const keyTimeLock: number = 24;      //答案过多少小时  就要锁上
const videoNum: number = 3;
/**
 * 关卡管理器
 */
export class LevelManager extends Singleton {
    static get ins() {
        return super.getInstance<LevelManager>();
    }
    unlockAllVideoNum: number = 0;
    unlockAllTime: number = null;
    unlockAllTime2: number = null;

    curLvInfo: LvInfo;
    curKeyInfo: any;

    curPageId: number = 1;//当前第几页


    isLiveing: boolean = false;

    private json: Array<LvInfo>;

    liveLvInfos: Array<LvInfo>;
    liveCurLvInfo: LvInfo;

    isSelectNewList: boolean = false;

    async init(callback) {
        if (AdManager.gameType == GAME_TYPE_ENUM.NAO_DONG_TIAN_HUA_BAN && AdManager.gameId != 29 && AdManager.gameId != 40) {
            console.log("获取本地关卡配置");
            await this.loadLocalJson(callback);
            return;
        }
        if (AdManager_ZJ.ins.gameId != 0 || AdManager_WX.ins.gameId != 0 || AdManager.gameType == GAME_TYPE_ENUM.Luan_DOU_DA_BI_PIN || AdManager_KS.ins.gameId != 0) {
            console.log("获取服务器关卡配置");
            AdManager.loadServerJson(async (lvJson) => {
                if (lvJson) {
                    this.json = lvJson;
                    this.initLocalJson();
                    callback();
                } else {
                    await this.loadLocalJson(callback);
                }
            });
        } else {
            await this.loadLocalJson(callback);
        }
    }

    async loadLocalJson(callback) {
        // let jsonAssets = await ResManager.ins.loadRes('json/LvInfos', cc.JsonAsset, BUNDLE_TYPE_ENUM.HOME_EXTRA);
        let jsonAssets = await ResManager1.ins.loadRes('json/LvInfos', cc.JsonAsset, BUNDLE_TYPE_ENUM.HOME);
        this.json = jsonAssets.json;
        this.initLocalJson();
        callback();
    }

    initLocalJson() {
        // let jsonAssets = await ResManager.ins.loadRes('json/LvInfos', cc.JsonAsset, BUNDLE_TYPE_ENUM.HOME_EXTRA);
        // this.json = jsonAssets.json;
        for (let i = 0; i < this.json.length; i++) {
            let info = this.json[i];
            if (!info.display) {
                this.json.splice(i, 1);
                i--;
                continue;
            }
            if (i == 0 || AdManager.isUnlockAllLevel()) { //OV渠道默认全部解锁
                this.unlockLevel(info.type, info.lv);
            }
        }

        this.initUnlockAllVideoNum();
    }

    /** 初始化解锁全部功能的看视频数 */
    initUnlockAllVideoNum() {
        this.unlockAllTime = Tools.getStorage("unlockAllTime");
        this.unlockAllTime2 = Tools.getStorage("unlockAllTime2");
        this.unlockAllVideoNum = Tools.getStorage("unlockAllVideoNum");
        if (this.unlockAllTime) {
            let hourDiff = TimeTools._ins.getHourTimeDiff(this.unlockAllTime);
            if (hourDiff <= unlockAllTime)
                this.unlockAllVideoNum = videoNum;
            else {
                if (this.unlockAllVideoNum === videoNum) {
                    this.unlockAllVideoNum = 0;
                }
            }
        } else {
            if (!this.unlockAllVideoNum) {
                this.unlockAllVideoNum = 0;
            }
        }
    }
    /** 本关bundle名称 */
    getBundleName() {
        return this.curLvInfo.type + "_" + this.curLvInfo.lv;
    }
    /** 获取达人推荐关卡 */
    getRecommendLevel() {
        return this.json.find(i => i.display && i.recommend)
    }
    /** 所有关 */
    getLvInfoArr() {
        if (AdManager.gameId === 5) {
            return this.json || null;
        } else if (this.json) {
            let normalJson = [];
            for (let item of this.json) {
                if (!item["isOnlyNew"]) {
                    normalJson.push(item);
                }
            }
            return normalJson;
        } else {
            return null;
        }
    }
    /**获取最新关卡列表 */
    getNewListInfoArr() {
        let newList = [];
        for (let item of this.json) {
            if (item.display && item["isNewList"] && item["isNewList"] === 1) {
                newList.push(item);
            }
            if (item.display && item["isOnlyNew"] && item["isOnlyNew"] === 1) {
                newList.push(item);
            }
        }
        newList.sort((a, b) => {
            if (a["sort"] && b["sort"]) {
                return a.sort - b.sort;
            }
        })
        for (let i = 0; i < newList.length; i++) {
            if (i === 0) {
                this.unlockLevel(newList[i].type, newList[i].lv);
                break;
            }
        }
        return newList;
    }

    /** 获取当前关所在页 */
    getCurrentLevelPageIdx(levelNumInPage: number) {
        if (!this.curLvInfo) return 0;
        let idx = this.json.findIndex(i => i.type === this.curLvInfo.type && i.lv === this.curLvInfo.lv);
        //索引0开始 故+1
        return Math.ceil((idx + 1) / levelNumInPage);
    }
    /** 关卡是否已经全部解锁 */
    isUnlockAll() {
        if (AdManager.releaseType === RELEASE_TYPE_ENUM.oppo_mini || AdManager.releaseType === RELEASE_TYPE_ENUM.vivo_mini) {
            return true;
        }
        return this.unlockAllVideoNum >= videoNum;
    }
    /** 关卡是否已经解锁 */
    isLevelUnlock(type: number, lv: number) {
        // cc.log("isLevelUnlock", this.unlockAllVideoNum)
        if (this.isUnlockAll()) {
            return true;
        }
        let finished = Tools.getStorage("pass" + type + "_" + lv);
        if (!finished) {
            let unlock = Tools.getStorage("unlock" + type + "_" + lv);
            if (!unlock) {
                unlock = false;
                // 检测是否临时解锁中
                let tempUnlock = Tools.getStorage("unlockTemp" + type + "_" + lv);
                if (tempUnlock != null) {
                    let unlockTime = Tools.getStorage("unlockTime" + type + "_" + lv);
                    if (unlockTime != null && TimeTools._ins.getHourTimeDiff(unlockTime) <= levelTimeLock) {
                        unlock = true;
                    }
                }
            }
            return unlock;
        } else {
            return finished;
        }
    }
    /** 获取关卡信息 */
    getNextLvInfo() {
        let idx = this.json.findIndex(i => i.type === this.curLvInfo.type && i.lv === this.curLvInfo.lv);
        // cc.log(idx, this.curLvInfo)
        if (idx > -1 && idx < this.json.length - 1) {
            return this.json[idx + 1];
        } else {
            return null;
        }
    }

    /**获取直播关卡信息 */
    getNextLiveLvInfo() {
        let idx = this.liveLvInfos.findIndex(i => i.type === this.curLvInfo.type && i.lv === this.curLvInfo.lv);
        if (idx > -1 && idx < this.liveLvInfos.length - 1) {
            return this.liveLvInfos[idx + 1];
        } else {
            return this.liveLvInfos[0];
        }
    }

    /** 获取关卡信息 */
    getLvInfo(type: number, lv: number) {
        return this.json.find(i => i.type === type && i.lv === lv);
    }
    /** 通过关卡在json中的下标 获取的信息配置 */
    getLvInfoByLvIdx(idx: number) {
        if (idx < 0 || idx > this.json.length - 1) return null;

        return this.json[idx];
    };
    /**获取关卡所在json下标 */
    getLvInfoIdx(type: number, lv: number) {
        let idx = this.json.findIndex(i => i.type === this.curLvInfo.type && i.lv === this.curLvInfo.lv);
        return idx;
    }
    /** 获取当前类型的所有关卡 */
    getLvInfosByType(type: number) {
        let infos = [];
        this.json.forEach(i => i.type === type ? infos.push(i) : void 0);
        return infos;
    }
    watchAllVideo() {
        this.unlockAllVideoNum++;
        Tools.setStorage("unlockAllVideoNum", this.unlockAllVideoNum);
        if (this.isUnlockAll()) {
            this.saveUnlockAllLevelTime();
        }
    }

    /**解锁全部关卡6小时 */
    watchAllVideo2() {
        this.unlockAllVideoNum++;
        Tools.setStorage("unlockAllVideoNum", this.unlockAllVideoNum);
        if (this.isUnlockAll()) {
            this.saveUnlockAllLevelTime2();
        }
    }

    /** 储存解锁所有关时间 */
    saveUnlockAllLevelTime() {
        Tools.setStorage("unlockAllTime", new Date().getTime());
    }
    /** 储存解锁所有关时间 6小时*/
    saveUnlockAllLevelTime2() {
        let unlockAllTime_ = Tools.getStorage("unlockAllTime");
        if (unlockAllTime_) { //如果有看视频解锁的24小时需要加上签到给的6h
            Tools.setStorage("unlockAllTime", unlockAllTime_ + unlockAllTime2 * 60 * 60 * 1000);
        } else {//如果没有全部解锁过 这里签到来的记录时间需要往后退24-6;
            Tools.setStorage("unlockAllTime", new Date().getTime() - (24 - unlockAllTime2) * 60 * 60 * 1000);
        }
    }
    /** 永久解锁当前关 */
    unlockCurrentLevel() {
        this.unlockLevel(this.curLvInfo.type, this.curLvInfo.lv)
    }
    /** 看视频临时解锁当前关 */
    unlockCurrentLevelTemp() {
        Tools.setStorage("unlockTemp" + this.curLvInfo.type + "_" + this.curLvInfo.lv, true);
        /** 看视频解锁的需要记录时效 */
        Tools.setStorage("unlockTime" + this.curLvInfo.type + "_" + this.curLvInfo.lv, new Date().getTime());
    }

    /** 解锁下一关 */
    unlockNextLevel() {
        let nextLvInfo = this.getNextLvInfo();
        if (nextLvInfo) {
            this.unlockLevel(nextLvInfo.type, nextLvInfo.lv);
        }
    }
    /** 解锁关 */
    unlockLevel(type: number, lv: number) {
        cc.log("unlockLevel", type + "_" + lv)
        Tools.setStorage("unlock" + type + "_" + lv, true);
    }

    /** 通过当前关 */
    finishCurrentLevel() {
        this.finishLevel(this.curLvInfo.type, this.curLvInfo.lv)
    }
    /** 通过关 */
    finishLevel(type: number, lv: number) {
        cc.log("finishLevel", type + "_" + lv)
        Tools.setStorage("pass" + type + "_" + lv, true);
    }

    /** 解锁提示1 */
    unlockLevelTip1() {
        Tools.setStorage("levelTips1_" + this.curLvInfo.type + "_" + this.curLvInfo.lv, true);
        Tools.setStorage("levelTips1Time_" + this.curLvInfo.type + "_" + this.curLvInfo.lv, new Date().getTime());
    }
    /** 解锁提示2 */
    unlockLevelTip2() {
        Tools.setStorage("levelTips2_" + this.curLvInfo.type + "_" + this.curLvInfo.lv, true);
        Tools.setStorage("levelTips2Time_" + this.curLvInfo.type + "_" + this.curLvInfo.lv, new Date().getTime());
    }

    /**添加直播关卡 */
    addLiveLv(lvInfo: LvInfo) {
        if (!this.liveLvInfos) {
            this.liveLvInfos = [];
        }
        this.liveLvInfos.push(lvInfo);
    }

    /**获取当前直播的关卡列表 */
    getLiveLvInfos() {
        if (!this.liveLvInfos) {
            this.liveLvInfos = [];
        }
        return this.liveLvInfos;
    }

    /**清除直播关卡列表 */
    removeLiveLvInfos() {
        this.liveLvInfos.length = 0;
    }


    /** 获取提示状态 */
    getAnswerState() {
        let unlockTip1 = Tools.getStorage("levelTips1_" + this.curLvInfo.type + "_" + this.curLvInfo.lv);
        let unlockTip1Time = Tools.getStorage("levelTips1Time_" + this.curLvInfo.type + "_" + this.curLvInfo.lv);
        if (unlockTip1Time != null && TimeTools._ins.getHourTimeDiff(unlockTip1Time) <= tipTimeLock) {
            unlockTip1 = true;
        } else {
            unlockTip1 = false;
        }

        let unlockTip2 = Tools.getStorage("levelTips2_" + this.curLvInfo.type + "_" + this.curLvInfo.lv);
        let unlockTip2Time = Tools.getStorage("levelTips2Time_" + this.curLvInfo.type + "_" + this.curLvInfo.lv);
        if (unlockTip2Time != null && TimeTools._ins.getHourTimeDiff(unlockTip2Time) <= keyTimeLock) {
            unlockTip2 = true;
        } else {
            unlockTip2 = false;
        }

        if (unlockTip1 && unlockTip2) {
            return ANSWER_STATE_ENUM.UNLOCK_ANSWER;
        } else if (unlockTip1 && !unlockTip2) {
            return ANSWER_STATE_ENUM.UNLOCK_TIP;
        } else {
            return ANSWER_STATE_ENUM.LOCKED;
        }
    }

    loadLevelPre(lvInfo?: LvInfo) {
        if (lvInfo) {
            LevelManager.ins.curLvInfo = lvInfo;
        }
        // UIManager.ins.showLoading();
        UIManager.ins.closeAll();
        UIManager.ins.showLevelPre('prefab/level/LevelPre_' + LevelManager.ins.curLvInfo.type);
    }
}